package easycloud.ecs;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;

public class SampleFileUtil {

	public static File getSampleEmptyFolder(int deep) throws IOException {
		File tempDir = FileUtils.getTempDirectory();
		File rootDir = new File(tempDir, RandomStringUtils.randomAlphabetic(4));
		if (!rootDir.exists()) {
			rootDir.mkdir();
		}
		File dir = rootDir;
		int curDeep = 0;
		while (curDeep++ < deep) {
			File nextDir = new File(dir, RandomStringUtils.randomAlphabetic(4));
			if (!nextDir.exists()) {
				nextDir.mkdir();
			}
			dir = nextDir;
		}
		return rootDir;
	}

	public static File getSampleFile() throws IOException {
		File file = File.createTempFile("sample", ".txt");
		Collection<String> lines = new ArrayList<String>(10);
		for (int i = 0; i < 10; i++) {
			lines.add(RandomStringUtils.randomAlphabetic(100));
		}
		FileUtils.writeLines(file, lines);
		return file;
	}

	public static File getSampleFolder(int deep) throws IOException {
		File tempDir = FileUtils.getTempDirectory();
		File rootDir = new File(tempDir, RandomStringUtils.randomAlphabetic(4));
		if (!rootDir.exists()) {
			rootDir.mkdir();
		}
		File dir = rootDir;
		int curDeep = 0;
		while (curDeep++ < deep) {
			File nextDir = new File(dir, RandomStringUtils.randomAlphabetic(4));
			if (!nextDir.exists()) {
				nextDir.mkdir();
			}
			for (int i = 0; i < 10; i++) {
				File tempFile = SampleFileUtil.getSampleFile();
				FileUtils.moveFileToDirectory(tempFile, dir, false);
			}
			dir = nextDir;
		}
		return rootDir;
	}

	private void printDir(File file) {
		if (file.isFile()) {
			System.out.println(file.getAbsolutePath());
		} else if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (File f : files) {
				printDir(f);
			}
		}
	}

	@Test
	public void testGetSampleDir() {
		try {
			File dir = SampleFileUtil.getSampleFolder(3);
			System.out.println(dir.getAbsolutePath());
			printDir(dir);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// @Test
	public void testGetSampleFile() {
		File file;
		try {
			file = SampleFileUtil.getSampleFile();
			System.out.println(file.getAbsolutePath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
